package com.xy6.concurrencyart.chapter03;

/**
 * final域示例
 * 
 * @author zhang
 * @since 2018-05-23
 */
public class FinalExample {
	// 普通变量
	int i;
	// final变量
	final int j;
	static FinalExample obj;

	public FinalExample() {
		// 写普通域
		i = 1;
		// 写final域
		j = 2;
	}

	// 写线程A执行
	public static void writer() {
		obj = new FinalExample();
	}

	// 读线程B执行
	public static void reader() {
		// 读对象引用
		FinalExample object = obj;
		// 读普通域
		int a = object.i;
		// 读final域
		int b = object.j;
		System.out.println(String.format("a:%d, b:%d", a, b));
	}

	public static void main(String[] args) throws InterruptedException {
		for(int i=0; i<1000; i++){
			Thread t1 = new Thread(new Runnable(){
				@Override
				public void run(){
					FinalExample.writer();
				}
			});
			Thread t2 = new Thread(new Runnable(){
				@Override
				public void run(){
					FinalExample.reader();
				}
			});
			t1.start();
			t1.join();
			t2.start();
			t2.join();
		}
	}

}
